// pages/detail/index.js
const wxParse = require('../../wxParse/wxParse.js')
import {
  DetailModel
} from '../../model/DetailModel.js'

const detailModel = new DetailModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    postId:null,
    title: '',
    author: '',
    categories:null,
    date:'',
    likeStatus:false,
    likeCount:null,
    comments_number:'',
    page_views: '',
    tags:null
  },
  /**
   * 生命周期函数--监听页面加载
   * 
   */
  onLoad: function(options) {
    let status = this.getLikeStorage(options.id)
    this.setData({
      likeStatus:status?true:false
    })
    wx.showLoading({
      title: 'Loading',
    })
    detailModel.getPostById(options.id).then(res=>{
      let postInfo = res.data[0]
      if(postInfo){  
        this.setData({
          postId: postInfo.post_id,
          title: postInfo.title,
          author: postInfo.author_name,
          date: postInfo.date,
          categories: postInfo.category_names,
          likeCount: postInfo.like_count ? postInfo.like_count : 0,
          comments_number: postInfo.comments_number,
          page_views: postInfo.views,
          tags:postInfo.tags
        })
        wxParse.wxParse('article', 'html', postInfo.content, this, 5);
        wx.hideLoading();
      }
    })
  },
  onLike:function(event){
    if(event.detail.status){
      detailModel.addLikeById(this.data.postId).then(res => {
        this.setLikeStorage(res.data)
       this.setData({
         likeStatus:true,
         likeCount:res.data
       })
      })
    }else{
      wx.showToast({
        title: '已经点过赞了',
        icon:'none',
        duration: 500
      })
    }
   
  },
  getKey(postid=null){
    
    return `post-${postid?postid:this.data.postId}` 
  }
  ,
  setLikeStorage(data){
    wx.setStorageSync(this.getKey(), data);
  },
  getLikeStorage(postid){
    let data = wx.getStorageSync(this.getKey(postid));
    console.log(data);
    return data;
  }
})